package com.yl.immodule.fragment.model;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.android.yl.ylicpsdk.ICPRtcEventHandler;
import com.android.yl.ylicpsdk.ICPRtcManager;
import com.camera.base.v.models.BaseViewModel;
import com.unionbroad.greendao.ChatMessage;
import com.unionbroad.greendao.MessageDialogue;

import java.util.ArrayList;
import java.util.List;

public class MessageListViewModel extends BaseViewModel {
    private static final String TAG = "MessageListViewModel";
    
    // 消息对话列表数据
    private final MutableLiveData<List<MessageDialogue>> _dialogueList = new MutableLiveData<>(new ArrayList<>());
    public final LiveData<List<MessageDialogue>> dialogueList = _dialogueList;
    
    // 加载状态
    private final MutableLiveData<Boolean> _isLoading = new MutableLiveData<>(false);
    public final LiveData<Boolean> isLoading = _isLoading;
    
    // 事件处理器
    private final ICPRtcEventHandler eventHandler = new ICPRtcEventHandler() {
        @Override
        public void onNewConversationCreated(MessageDialogue messageDialogue) {
            loadConversations();
        }
        
        @Override
        public void onMessageArrived(ChatMessage message) {
            // 触发刷新以更新最后一条消息
            loadConversations();
        }
    };
    
    public MessageListViewModel() {
        ICPRtcManager.getsInstance().addEventHandler(eventHandler);
        loadConversations();
    }
    
    public void loadConversations() {
        _isLoading.setValue(true);
        List<MessageDialogue> conversations = ICPRtcManager.getsInstance().getAllConversation();
        _dialogueList.setValue(new ArrayList<>(conversations));
        _isLoading.setValue(false);
    }
    
    public void deleteConversation(long chatId) {
        ICPRtcManager.getsInstance().deleteConversation(chatId);
        ICPRtcManager.getsInstance().deleteConversationMessages(chatId);
        loadConversations();
    }
    
    @Override
    protected void onCleared() {
        super.onCleared();
        ICPRtcManager.getsInstance().removeEventHandler(eventHandler);
    }
} 